﻿using JshRCSWebApi.Util.Cache;
using JshRCSWebApi.Util.Cache.Redis;
using JshRCSWebApi.Util.DataAccess;

namespace JshRCSWebApi.API.Utility.JwtConfig
{
    public class AuthenticationFilter : IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var path = context.HttpContext.Request.Path;
            if ("/api/User/Login".Equals(path)) return;
            string bearer = context.HttpContext.Request.Headers["Authorization"].FirstOrDefault();
            if (string.IsNullOrEmpty(bearer) || !bearer.Contains("Bearer"))
            {
                throw new CustomException(401, "don't catch token");
            }
            string[] jwt = bearer.Split(' ');

            ClaimsPrincipal claimsPrincipal = context.HttpContext.User;
            var UID = (claimsPrincipal)?.Claims.FirstOrDefault(c => c.Type == "ID").Value;

            
            var tokenInfo = RedisFn.fn_redis_get_string($"user_{Convert.ToInt32(UID)}"); 

         /*   if (!string.IsNullOrEmpty(tokenInfo))
            {
               var timestamp =  tokenInfo.Split(",")[1];
               var pastTime = DateTimeConvert.ConvertStringToDateTime(long.Parse(timestamp));
               var timeDifference = DateTime.Now - pastTime;
               if (Math.Abs(timeDifference.TotalMinutes)  > 3)
               {
                   throw new CustomException(401, "token expire");
               }
               else
               {
                   RedisFn.fn_redis_setExpire($"user_{Convert.ToInt32(UID)}", TimeSpan.FromMinutes(3)); //延长过期时间
                   RedisFn.fn_redis_save_string($"user_{Convert.ToInt32(UID)}", $"{jwt[1]},{DateTimeConvert.DateTimeToTimestamp(DateTime.Now)}"); //更新key value
               }
            }
            else
            {
                throw new CustomException(401, "token has been removed");
            }*/
        }
    }
}
